package com.demo.youxuanmall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.Category;
import com.demo.youxuanmall.entity.Product;
import com.demo.youxuanmall.service.CategoryService;
import com.demo.youxuanmall.service.ProductService;
import com.demo.youxuanmall.service.SystemSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Controller
@RequestMapping("/category")
public class CategoryController extends BaseController {

    private final CategoryService categoryService;
    private final ProductService productService;

    public CategoryController(
            SystemSettingService systemSettingService,
            CategoryService categoryService,
            ProductService productService) {
        super(systemSettingService);
        this.categoryService = categoryService;
        this.productService = productService;
    }

    @GetMapping
    public String categoryList(Model model) {
        try {
            // 获取所有启用的分类
            List<Category> categories = categoryService.list(
                new LambdaQueryWrapper<Category>()
                    .eq(Category::getStatus, 1)
                    .orderByAsc(Category::getSort)
            );
            
            model.addAttribute("categories", categories);
            
            // 如果有分类，默认显示第一个分类的商品
            if (!categories.isEmpty()) {
                Category firstCategory = categories.get(0);
                List<Product> products = productService.list(
                    new LambdaQueryWrapper<Product>()
                        .eq(Product::getCategoryId, firstCategory.getId())
                        .eq(Product::getStatus, 1)
                        .eq(Product::getIsDeleted, 0)
                );
                
                model.addAttribute("currentCategory", firstCategory);
                model.addAttribute("products", products);
            }
            
            return "category/list";
        } catch (Exception e) {
            log.error("加载分类页面失败", e);
            model.addAttribute("error", "加载分类页面失败，请稍后重试");
            return "category/list";
        }
    }

    @GetMapping("/{id}")
    public String categoryProducts(
            @PathVariable Long id,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "12") Integer size,
            Model model) {
        try {
            // 获取所有启用的分类
            List<Category> categories = categoryService.list(
                new LambdaQueryWrapper<Category>()
                    .eq(Category::getStatus, 1)
                    .eq(Category::getIsDeleted, 0)
                    .orderByAsc(Category::getSort)
            );
            
            model.addAttribute("categories", categories);
            
            // 获取当前分类
            Category currentCategory = categoryService.getById(id);
            if (currentCategory == null || currentCategory.getStatus() != 1 || currentCategory.getIsDeleted() != 0) {
                model.addAttribute("error", "分类不存在或已禁用");
                return "category/list";
            }
            
            // 获取当前分类下的商品（使用分页）
            Page<Product> pageParam = new Page<>(page, size);
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Product::getCategoryId, id)
                    .eq(Product::getStatus, 1)
                    .eq(Product::getIsDeleted, 0)
                    .orderByDesc(Product::getCreateTime);
            
            Page<Product> productPage = productService.page(pageParam, wrapper);
            
            model.addAttribute("currentCategory", currentCategory);
            model.addAttribute("products", productPage.getRecords());
            model.addAttribute("total", productPage.getTotal());
            model.addAttribute("pages", productPage.getPages());
            model.addAttribute("current", productPage.getCurrent());
            model.addAttribute("size", productPage.getSize());
            
            return "category/list";
        } catch (Exception e) {
            log.error("加载分类商品失败: categoryId={}, page={}, size={}", id, page, size, e);
            model.addAttribute("error", "加载分类商品失败，请稍后重试");
            return "category/list";
        }
    }

    /**
     * 获取分类列表
     */
    @GetMapping("/list")
    @ResponseBody
    public Result<List<Category>> getCategoryList() {
        try {
            LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Category::getStatus, 1)
                    .eq(Category::getIsDeleted, 0)
                    .orderByAsc(Category::getSort);
            List<Category> categories = categoryService.list(wrapper);
            return Result.success(categories);
        } catch (Exception e) {
            log.error("获取分类列表失败", e);
            return Result.error("获取分类列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取分类下的商品
     */
    @GetMapping("/{id}/products")
    @ResponseBody
    public Result<Page<Product>> getCategoryProducts(
            @PathVariable Long id,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "12") Integer pageSize) {
        try {
            // 检查分类是否存在且可用
            Category category = categoryService.getById(id);
            if (category == null || category.getStatus() != 1 || category.getIsDeleted() != 0) {
                return Result.error("分类不存在或已禁用");
            }

            // 获取该分类下的商品
            Page<Product> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Product::getCategoryId, id)
                    .eq(Product::getStatus, 1)
                    .eq(Product::getIsDeleted, 0)
                    .orderByDesc(Product::getCreateTime);
            
            Page<Product> productPage = productService.page(page, wrapper);
            return Result.success(productPage);
        } catch (Exception e) {
            log.error("获取分类商品失败", e);
            return Result.error("获取分类商品失败：" + e.getMessage());
        }
    }
} 